/*
 * JOY.c
 *
 * Created: 12.09.2012 19:04:25
 *  Author: mariuvi
 */
#include "USART.h"
#include "JOY.h"
#include "ADC.h"
#include <util/delay.h>
#include "definitions.h"
#include <avr/io.h>

#define JOY_X_CH 1
#define JOY_Y_CH 2
#define DEADZONE 5
 
static JOY_Pos JOY_mid;

void JOY_calibration()
{
	JOY_mid.x = (int)ADC_read(JOY_X_CH);
	JOY_mid.y = (int)ADC_read(JOY_Y_CH);				
}

JOY_Pos JOY_read()
{
	JOY_Pos JOY_position;
	int range;
	//Reads the joysticks position	
	JOY_position.x = (int)ADC_read(JOY_X_CH);
	JOY_position.y = (int)ADC_read(JOY_Y_CH);
	
	range = JOY_position.x - JOY_mid.x;
	if(range > DEADZONE)
	{
		JOY_position.x = 100*range/(255- JOY_mid.x);
	}
	else if(range < -DEADZONE)
	{
		JOY_position.x = 100*range/(JOY_mid.x);
	}
	else
	{
		JOY_position.x = 0;	
	}
	
	range = JOY_position.y - JOY_mid.y;
	
	if(range > DEADZONE)
	{
		JOY_position.y = 100*range/(255 - JOY_mid.y);
	}
	else if(range < -DEADZONE)
	{
		JOY_position.y = 100*range/(JOY_mid.y);
	}
	else
	{
		JOY_position.y = 0;
	}
	
	//Sets the joysticks direction
	if((JOY_position.x == 0) && (JOY_position.y == 0))
	{
		JOY_position.dir = NEUTRAL;
	}
	else if(abs(JOY_position.x) > abs(JOY_position.y)) //x dominates y
	{
		if(JOY_position.x > 0)
		{
			JOY_position.dir = RIGHT;
		}
		else
		{
			JOY_position.dir = LEFT;
		}
	}
	else
	{
		if(JOY_position.y > 0)
		{
			JOY_position.dir = UP;
		}
		else
		{
			JOY_position.dir = DOWN;
		}
	}
	return JOY_position;
}

int JOY_button_pressed()
{
	return !(PINB & (1<<PINB0));
}

void JOY_button_init()
{
	BIT_SET(DDRB, DDB0);
	BIT_SET(PORTB, PORTB0);
}